﻿using System.Linq;
using System.Reflection;

namespace Basmus.Values.Attributive
{
    public class PropertyInfoBuilder : IPropertyInfoBuilder
    {
        public PropertyInfo Build(ValuesContext valuesContext)
        {
            var properties = valuesContext
                .ModelContext
                .TargetType
                .GetProperties();
            var property = properties
                .Where(x => x
                                .GetCustomAttributes(typeof (NameAttribute), false)
                                .Cast<NameAttribute>()
                                .Where(y => y.Key == valuesContext.ModelContext.SchemeKey)
                                .Where(y => y.Name == valuesContext.Name)
                                .Any())
                .FirstOrDefault();
            if (property == null)
            {
                property = properties
                    .Where(x => x
                                    .GetCustomAttributes(typeof (NameAttribute), false)
                                    .Cast<NameAttribute>()
                                    .Where(y => y.Key == SchemeKey.Default)
                                    .Where(y => x.Name == valuesContext.Name)
                                    .Any())
                    .FirstOrDefault();
            }
            if (property == null)
            {
                property = properties
                    .Where(x => x.Name == valuesContext.Name)
                    .FirstOrDefault();
            }
            return property;
        }
    }
}